package com.fdq.dianping.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fdq.dianping.entity.Shop;
import com.fdq.dianping.entity.ShopComment;
import com.fdq.dianping.mapper.ShopCommentMapper;
import com.fdq.dianping.service.IShopCommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fdq.dianping.service.IShopService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author fdq
 * @since 2025-01-25
 */
@Service
public class ShopCommentServiceImpl extends ServiceImpl<ShopCommentMapper, ShopComment> implements IShopCommentService {

    @Resource
    private IShopService shopService;

    @Resource
    private ShopCommentMapper shopCommentMapper;

    @Override
    //@Scheduled(cron = "0 0 0 * * ?")        // 每天凌晨0点执行
    @Scheduled(cron = "0 12 15 * * ?")
    public void updateScore() {
        //今天的日期
        LocalDateTime now = LocalDateTime.now();
        // 获取昨天0点的时间
        LocalDateTime startOfDayYesterday = now.minusDays(1).toLocalDate().atStartOfDay();
        // 获取昨天24点的时间（即今天的0点）
        LocalDateTime endOfDayYesterday = now.toLocalDate().atStartOfDay();
        //获取昨天的全部评论数量
        List<ShopComment> yesterdayComments = shopCommentMapper.selectByDateRange(startOfDayYesterday.toString(), endOfDayYesterday.toString());


        //将昨天的评论以商户id为key，score为值转成map
        //相同的商户评分相加
        Map<Long, Integer> shopCommentScoreMap = yesterdayComments.stream()
                .collect(Collectors.toMap(ShopComment::getShopId, ShopComment::getScore
                        , Integer::sum));        //某个商户评分相加


        //昨天商户评论数量map
        Map<Long, Long> shopCommentAccountMap = yesterdayComments.stream()
                .collect(Collectors.groupingBy(ShopComment::getShopId,Collectors.counting()));

        //更新昨天评论的商户的得分与评论数量
        shopCommentAccountMap.forEach((shopId,commentAccount) -> {
            Shop shop = shopService.getById(shopId);
            //更新评论数量
            int commentsNew = Math.toIntExact(commentAccount);
            int commentsOld = shop.getComments();
            shop.setComments(commentsNew + commentsOld);

            //更新得分
            int totalScore = shop.getScore() * commentsOld + shopCommentScoreMap.get(shopId);
            Integer scoreNew = totalScore / (commentsNew + commentsOld);
            shop.setScore(scoreNew);
            shopService.updateById(shop);
        });

    }
}
